//
//  MyReceiveAddressViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/18.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "MyReceiveAddressViewController.h"
#import "AddressManagementTableViewCell.h"
#import "TheNewAddressTableViewController.h"


@interface MyReceiveAddressViewController () <AddressManagementDelegate , UITableViewDelegate , UITableViewDataSource>

@property (nonatomic , strong) NSMutableArray *dataArray;
@property (nonatomic , strong) NSMutableDictionary *userData;
@property (nonatomic , strong) UIBarButtonItem *rightBarButtonItem;
@property (nonatomic , strong) UIView *noView;   /**<没有地址view*/
@property (nonatomic , strong) UITableView *tableView;

@end

@implementation MyReceiveAddressViewController (NetWorking)

- (void)getAddressListByCreatorMobile{
    NSDictionary *data = @{@"auId":[UserModel sharedInstanced].userId};
    [[AFAppDotNetAPIClient sharedClient]POST:@"LaundryMall/Login_Registration/displayUserAddress.action" parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSArray *array = responseObject[@"obj"];
            [self hiddenProgressHUD];
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:array];
                [self.tableView reloadData];
            for (NSDictionary *dic in array) {
                if ([dic[@"ua_default"] isEqualToString:@"1"]) {
                    [UserModel sharedInstanced].address = dic[@"ua_address"];
                }
            }
            
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

/**
 设置默认地址
 */
- (void)modifyDefaults:(NSDictionary *)model{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"ua_id":model[@"ua_id"],
                                 @"ua_default":@"1"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Login_Registration/modifyDefaults.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
         ShowMessage(responseObject[@"msg"]);
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [UserModel sharedInstanced].address = model[@"ua_address"];
            [self getAddressListByCreatorMobile];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

@implementation MyReceiveAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地址管理";
    self.navigationItem.rightBarButtonItem = self.rightBarButtonItem;
    [self.view addSubview:self.tableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getAddressListByCreatorMobile];
}

#pragma mark -  init

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        _tableView.backgroundColor = getColor(@"eeeeee");
        self.userData = [NSMutableDictionary dictionary];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIBarButtonItem *)rightBarButtonItem{
    if (!_rightBarButtonItem) {
        _rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    }
    return _rightBarButtonItem;
}

#pragma mark - click

- (void)rightBarButtonItemClick{
    NSLog(@"新增");
    TheNewAddressTableViewController *VC = [[TheNewAddressTableViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
    
}

#pragma mark - <AddressManagementDelegate>

/**
 选择代理事件
 */
- (void)getDefault:(AddressManagementTableViewCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self modifyDefaults:self.dataArray[indexPath.section]];
}

/**
 编辑代理事件
 */
- (void)getEditorClcik:(AddressManagementTableViewCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    TheNewAddressTableViewController *VC = [TheNewAddressTableViewController new];
    VC.model = self.dataArray[indexPath.section];
    VC.type = kTheNewAddressTypeEndit;
    [self.navigationController pushViewController:VC animated:YES];
}

///**
// 删除点击事件
// */
//- (void)getDeleteClick:(AddressManagementTableViewCell *)cell{
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"您确认删除%@",self.dataArray[indexPath.section][kName]] preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"123");
//    }];
//    [alertC addAction:ok];
//    [alertC addAction:cancel];
//    [self presentViewController:alertC animated:YES completion:nil];
//}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10 / WIDTH_5S_SCALE;
}

////左划效果
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return UITableViewCellEditingStyleDelete;
//}
//
//- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0){
//    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
//        //                [tableView beginUpdates];
//        //有时候不加注释的方法会报错
//        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"您确认删除%@",self.dataArray[indexPath.section][kName]] preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            NSDictionary *data = @{@"aId":self.dataArray[indexPath.section][@"aId"]};
//            //有时候不加注释的方法会报错
//            [[AFAppDotNetAPIClient sharedClient]POST:@"http://114.215.30.226/xct/user/deleteAddressByaId.action" parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                [self getAddressListByCreatorMobile];
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                [self showError:error];
//            }];
//        }];
//        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            NSLog(@"123");
//        }];
//        [alertC addAction:ok];
//        [alertC addAction:cancel];
//        [self presentViewController:alertC animated:YES completion:nil];
//        //        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//        //        [tableView endUpdates];
//    }];
//    action1.backgroundColor = [UIColor redColor];
//    
//    return @[action1];
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *text = self.dataArray[indexPath.section][@"address"];
    CGRect frame = [text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 20 / WIDTH_5S_SCALE, NSIntegerMax) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:DEF_FontSize_15} context:nil];
    return 75 / WIDTH_5S_SCALE + frame.size.height + 45;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_getAddress) {
        [self.navigationController popViewControllerAnimated:YES];
        _getAddress(self.dataArray[indexPath.section][@"ua_address"]);
    }
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressManagementTableViewCell *cell = [AddressManagementTableViewCell cellForTableView:tableView];
    cell.delegade = self;
    NSLog(@"%@",self.dataArray);
    cell.model = self.dataArray[indexPath.section];
    return cell;
}

#pragma mark - data

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    
    return _dataArray;
}

@end
